package com.example.pixelyear.view;

import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ScrollView;

//解决滑动冲突
public class MyScrollView extends ScrollView {

    private EditText text;

    public MyScrollView(Context context) {
        this(context, null);
    }

    public MyScrollView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public MyScrollView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        if (getChildCount() > 0) {
            View childAt = getChildAt(0);
            if (childAt instanceof EditText)
                text = (EditText) childAt;
        }
    }

    float x = 0;
    float y = 0;

    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            x = ev.getRawX();
            y = ev.getRawY();
        } else if (ev.getAction() == MotionEvent.ACTION_UP) {
            if (Math.abs(ev.getRawX() - x) < 10 && Math.abs(ev.getRawY() - y) < 10 && text != null) {
                showKeyBroad();
                return true;
            }
        }
        return super.onTouchEvent(ev);
    }

    private void showKeyBroad() {
        text.setFocusable(true);
        text.setFocusableInTouchMode(true);
        text.requestFocus();
        InputMethodManager imm = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.showSoftInput(text, 0);
        text.setSelection(text.getText().length());
    }
}
